﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MyMusicCollection.Model
{
	class CollectionHandler
	{
		private AlbumHandler mAlbumHandler = new AlbumHandler();

		public List<ArtistAlbum> GetCollection()
		{
			//Om collectionfilen inte finns
			if (File.Exists("collection.dat") == false)
			{
				return null;
			}

			List<ArtistAlbum> albumCollection = new List<ArtistAlbum>();
			ArtistAlbum album = null;
			TextReader tr = new StreamReader("collection.dat");
			string line;

			//Om collectionfilen  är tom
			if (tr.Peek() < 0)
			{
				return null;
			}

			while (tr.Peek() >= 0)
			{
				line = tr.ReadLine();
				
				//Starttag
				if (line == "_albumstart_")
				{
					album = new ArtistAlbum();
				}

				//ReleaseID
				if (line == "_releaseid_")
				{
					album.mID = int.Parse(tr.ReadLine());
				}

				//Artist
				if (line == "_artist_")
				{
					album.mArtist = tr.ReadLine();
				}

				//Albumtitel
				if (line == "_title_")
				{
					album.mTitle = tr.ReadLine();
				}

				//Format
				if (line == "_format_")
				{
					album.mFormat = tr.ReadLine();
				}

				//Label
				if (line == "_label_")
				{
					album.mLabel = tr.ReadLine();
				}

				//År
				if (line == "_year_")
				{
					album.mYear = tr.ReadLine();
				}

				//Sluttag
				if (line == "_albumend_")
				{
					albumCollection.Add(album);
				}
			}

			//TODO Borde ha så den sorterar efter år efter att den sorterat efter artist
			//Sortering efter artist
			albumCollection.Sort(delegate(ArtistAlbum a1, ArtistAlbum a2)
			{
				return a1.mArtist.CompareTo(a2.mArtist);
			});

			tr.Close();

			return albumCollection;
		}

		public void AddToCollection(ArtistAlbum aAlbum)
		{
			TextWriter tw = new StreamWriter("collection.dat", true);

			tw.WriteLine("_albumstart_");

			//ReleaseID
			tw.WriteLine("_releaseid_");
			tw.WriteLine(aAlbum.mID);

			//Artist
			tw.WriteLine("_artist_");
			tw.WriteLine(aAlbum.mArtist);

			//Titel
			tw.WriteLine("_title_");
			tw.WriteLine(aAlbum.mTitle);

			//Format
			tw.WriteLine("_format_");
			tw.WriteLine(aAlbum.mFormat);

			//Label
			tw.WriteLine("_label_");
			tw.WriteLine(aAlbum.mLabel);

			//Year
			tw.WriteLine("_year_");
			tw.WriteLine(aAlbum.mYear);

			tw.WriteLine("_albumend_");

			tw.Close();
		}
	}
}
